package com.qianniu.napi.admin.task;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.base.Strings;
import com.qianniu.napi.admin.entity.*;
import com.qianniu.napi.admin.entity.penum.RefundEnum;
import com.qianniu.napi.admin.mapper.OrderMapper;
import com.qianniu.napi.admin.mapper.StoreMapper;
import com.qianniu.napi.admin.mapper.StoreStatMapper;
import com.qianniu.napi.admin.service.IGoodsService;
import com.qianniu.napi.admin.service.IOrderService;
import com.qianniu.napi.admin.service.IStoreService;
import com.qianniu.napi.common.config.Constants;
import com.qianniu.napi.common.util.ImageUtil;
import com.qianniu.napi.common.util.ObjectUtil;
import com.qianniu.napi.common.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Configuration
@Component // 此注解必加
@EnableScheduling // 此注解必加
public class StoreTask {

    private static final Logger logger = LoggerFactory.getLogger(StoreTask.class);

    @Autowired
    private IStoreService storeService;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private StoreMapper storeMapper;
    @Autowired
    private OrderMapper orderMapper;

    private final static String rootsite = "https://img.niucaiduo.com";


//    @Scheduled(cron = "0 23 * * * ?")
    public void checkStoreImage() {
        logger.debug(">>>>>>>>>>>>>>>>>>checkStoreImage start");

        Integer index = 1;
        Integer limit = 100;
        boolean flag = true;
        while (flag) {
            Wrapper<Store> wrapper = new EntityWrapper<Store>()
                    .setSqlSelect("id,thumb,pic,photos,xiangqing,zhizhao,xukezheng").ne("mpid",89);

            Page page = new Page(index,limit);
            Page<Store> list = storeService.selectPage(page,wrapper);

            logger.debug(">>>>>>>>>>>>>>>>>>checkStoreImage list="+ JSON.toJSONString(list.getRecords()));

            for (Store item : list.getRecords()) {
                logger.info("------------------------------for each start");

                if (!Strings.isNullOrEmpty(item.getPic())) {
                    String img = item.getPic().replace(rootsite, Constants.PATH_IMAGES);
                    ImageUtil.yasuo(img, 750, 540);
                }

                if (!Strings.isNullOrEmpty(item.getThumb())) {
                    String img = item.getThumb().replace(rootsite, Constants.PATH_IMAGES);
                    ImageUtil.yasuo(img, 200, 200);
                }

                if (!Strings.isNullOrEmpty(item.getPhotos())) {
                    String[] photos = item.getPhotos().replace(rootsite, Constants.PATH_IMAGES).split(";");
                    for (String img : photos) {
                        ImageUtil.yasuo(img, null, null);
                    }
                }

                if (!Strings.isNullOrEmpty(item.getXiangqing())) {
                    String[] photos = item.getXiangqing().replace(rootsite, Constants.PATH_IMAGES).split(";");
                    for (String img : photos) {
                        ImageUtil.yasuo(img, null, null);
                    }
                }

                if (!Strings.isNullOrEmpty(item.getZhizhao())) {
                    String[] photos = item.getZhizhao().replace(rootsite, Constants.PATH_IMAGES).split(";");
                    for (String img : photos) {
                        ImageUtil.yasuo(img, null, null);
                    }
                }

                if (!Strings.isNullOrEmpty(item.getXukezheng())) {
                    String[] photos = item.getXukezheng().replace(rootsite, Constants.PATH_IMAGES).split(";");
                    for (String img : photos) {
                        ImageUtil.yasuo(img, null, null);
                    }
                }
            }
            flag = list.getRecords() != null && list.getRecords().size() == limit;
            index++;
        }

        logger.debug(">>>refreshStock exe success");
    }


    @Scheduled(cron = "0 29 0 * * ?")
    public void checkStoreStat() {
        logger.debug(">>>>>>>>>>>>>>>>>>checkStoreStat start");

        Integer index = 1;
        Integer limit = 100;
        boolean flag = true;
        while (flag) {
            Wrapper<Store> wrapper = new EntityWrapper<Store>();

            Page page = new Page(index,limit);
            Page<Store> list = storeService.selectPage(page,wrapper);

            try {


            for (Store item : list.getRecords()) {
                logger.info("------------------------------for each start");
                StoreStat storeStat = new StoreStat();
                Long sid = item.getId();

                int dingdanshu = orderService.selectCount(new EntityWrapper<Order>().where("sid=" + sid + " and status>1"));
                storeStat.setOrders(dingdanshu);

                int huodongshu = goodsService.selectCount(new EntityWrapper<Goods>()
                        .where("sid=" + sid + " and type>0 and is_deleted=-1"));//营销活动type > 0
                storeStat.setGoods(huodongshu);

                Map map = new HashMap<String,String>();
                map.put("sid",sid);
                int shu = orderMapper.getHdCanyushu(map);
                storeStat.setUsers(shu);

                Order order = orderService.selectOne(new EntityWrapper<Order>()
                                        .setSqlSelect("sum(realpay) realpay,sum(minprice) minprice")
                                        .eq("sid",sid).gt("status",1));
                if(order!=null){
                    storeStat.setTotal(order.getRealpay());
                    storeStat.setMshoukuan(order.getMinprice());
                }else{
                    storeStat.setTotal(new BigDecimal(0));
                    storeStat.setMshoukuan(new BigDecimal(0));
                }

                Goods viewgoods = goodsService.selectOne(new EntityWrapper<Goods>()
                        .setSqlSelect("sum(views) views")
                        .eq("sid",sid));
                int v = item.getViews();
                if(viewgoods!=null)v+=viewgoods.getViews();

                storeStat.setViews(Long.valueOf(v));
                storeStat.setRenqi(item.getRenqi()==null?1:Long.valueOf(item.getRenqi()));

                int refunds = orderService.selectCount(new EntityWrapper<Order>()
                        .eq("sid",sid).eq("is_refund",1));
                storeStat.setRefunds(refunds);

                int hx = orderService.selectCount(new EntityWrapper<Order>()
                        .eq("sid",sid).ge("status",4));
                storeStat.setHexiaos(hx);

                storeStat.setStoreid(item.getId());
                storeStat.setStorename(item.getName());
                storeStat.setStorepic(item.getThumb()==null?item.getPic():item.getThumb());

                storeStat.setModifytime(new Date());
                storeStat.setMpid(item.getUid());

                logger.debug("--------------------------------------------storeStat="+JSON.toJSONString(storeStat));
                storeStat.insertOrUpdate();
            }
            }catch (Exception e){
                logger.error("-------------checkStoreStat",e);
            }

            flag = list.getRecords() != null && list.getRecords().size() == limit;
            index++;
        }

        logger.debug(">>>refreshStock exe success");
    }

}
